<script setup lang="ts">
import { reactive, onMounted, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { queryForm, createFromEntity, delForm } from '@/api/develop/form'
import { selectEntityByModId } from '@/api/develop/entity'
import { useAppStore } from '@/store/modules/app'
import { useI18n } from '@/hooks/web/useI18n'
import { useLocaleStoreWithOut } from '@/store/modules/locale'
import { Paging } from '@/config/public'
import { useEmitt } from '@/hooks/web/useEmitt'
import { useRouter } from 'vue-router'
import { selectModule } from '@/api/develop'
import { ModuleTree } from '@/components/Tree'

defineOptions({
  name: 'FormManage'
})

const appStore = useAppStore()
const { t } = useI18n()
const { push, currentRoute } = useRouter()
const localeStore = useLocaleStoreWithOut()
const curLang = localeStore.getCurrentLocale.lang
const formRef = ref()

const state = reactive({
  searchKey: '',
  // 表格數據
  tableView: [{}],
  // 分頁相關屬性
  totalCount: 0,
  pageSizes: Paging.sizes,
  queryBody: {
    key: '',
    pageNo: 1,
    pageSize: Paging.defaultSize,
    params: {
      'Q_f.status_I_LT': 4
    },
    sortField: '',
    sortOrder: ''
  },
  dialogVisible: false,
  dialogForm: { moduleId: '', entId: '', fmType: '1', fmCols: 2 },
  dialogRule: {
    moduleId: {
      required: true,
      message: t('orderNo.module') + t('common.notEmpty'),
      trigger: ['blur']
    },
    entId: {
      required: true,
      message: t('form.entity') + t('common.notEmpty'),
      trigger: ['blur']
    }
  },
  dialogModName: 'moduleName',
  fmNameField: 'fmName',
  entNameField: 'entName',
  modNameField: 'moduleName',
  createFormLoading: false,
  moduleList: [],
  entityList: []
})

onMounted(async () => {
  if (curLang == 'en') {
    state.fmNameField = 'enName'
    state.modNameField = 'enModuleName'
    state.dialogModName = 'enName'
    state.entNameField = 'enName'
  } else if (curLang == 'zh_HK') {
    state.fmNameField = 'hkName'
    state.modNameField = 'hkModuleName'
    state.dialogModName = 'hkName'
    state.entNameField = 'hkName'
  }
  state.moduleList = await selectModule()
  init()
})

const changePage = (page) => {
  state.queryBody.pageNo = page
  init()
}
const changePageSize = (pageSize) => {
  state.queryBody.pageSize = pageSize
  state.queryBody.pageNo = 1
  init()
}
// 刪除当前记录
const deleteOne = (row) => {
  ElMessageBox.confirm(t('common.delMessage'), t('common.warning'), {
    confirmButtonText: t('common.ok'),
    cancelButtonText: t('common.cancel'),
    type: 'warning'
  })
    .then(async () => {
      await delForm(row.fmId)
      init()
    })
    .catch(() => {})
}

// 修改
const edit = (id) => {
  push({
    name: 'FormAdd',
    query: {
      id: id
    }
  })
}
//设计
const design = (id) => {
  push({
    name: 'FormDesign',
    query: {
      id: id
    }
  })
}
//预览
const preview = (id) => {
  push({
    name: 'FormShow',
    query: {
      pkId: null,
      formId: id,
      readonly: 0,
      preview: 1,
      fromPath: '/Develop/FormManage'
    }
  })
}

// 发布到菜单
const add2Menu = (row) => {
  push({
    name: 'MenuEdit',
    query: {
      id: null,
      type: 'form',
      formId: row.fmId,
      name: row.fmName,
      hkName: row.hkName,
      enName: row.enName,
      fromPath: currentRoute.value.fullPath
    }
  })
}

/**
 * @description  定义列表刷新事件
 * @author Elwin ZHANG
 * @date 2022-06-08 11:44
 */
useEmitt({
  //刷新列表事件
  name: 'refreshFormList',
  callback: () => {
    handleSearch()
  }
})

// 搜索
const handleSearch = () => {
  state.queryBody.key = state.searchKey
  init()
}

//重置查询
const resetSearch = () => {
  state.searchKey = ''
  state.queryBody.params['Q_f.module_id_S_IN'] = ''
  handleSearch()
}

//点击模块树节点
const handleNodeClick = (data) => {
  state.queryBody.params['Q_f.module_id_S_IN'] = data
  state.dialogForm.moduleId = data.split(',')[0]
  handleSearch()
}

//渲染页面的接口
const init = async () => {
  appStore.setFooter(false)
  state.tableView = []
  await queryForm(state.queryBody)
    .then((res) => {
      const result = res as any
      var data = result.result.data
      state.tableView = data
      state.totalCount = result.result.totalCount
    })
    .catch(() => {})
}

//根据模块变化刷新实体列表
const refreshEntityList = async (event) => {
  state.entityList = (await selectEntityByModId(event)).data
}

//表单类型改变时事件
const changeType = (type) => {
  if (type == 1) {
    state.dialogForm.fmCols = 2
  } else {
    state.dialogForm.fmCols = 1
  }
}

//由实体创建表单
const createForm = async () => {
  state.createFormLoading = true
  const result = (await createFromEntity(state.dialogForm)) as any
  if (!result) {
    state.createFormLoading = false
    return
  }
  if (result.success) {
    ElMessage.success(t('form.created'))
    handleSearch()
    state.dialogVisible = false
  }
  state.createFormLoading = false
}

//显示创建表单对话框
const showDialog = () => {
  state.dialogForm.entId = ''
  if (state.dialogForm.moduleId) {
    refreshEntityList(state.dialogForm.moduleId)
  }
  state.dialogVisible = true
}
</script>
<template>
  <div>
    <!-- 搜索條件卡片 -->
    <el-card class="box-card">
      <el-row :gutter="10" style="padding: 5px 5px; line-height: 28px" align="middle">
        <el-col :sm="5" :md="4" style="text-align: right">{{ $t('common.searchKey') }}</el-col>
        <el-col :sm="19" :md="12" style="text-align: left">
          <el-input
            v-model="state.searchKey"
            @keyup.enter="handleSearch"
            :placeholder="$t('common.inputText') + $t('form.name') + '/' + $t('common.remark')"
          />
        </el-col>
        <el-col :sm="24" :md="8" style="text-align: right">
          <div style="margin-right: -5px">
            <el-button @click="handleSearch" type="primary" size="small" plain
              ><Icon icon="ic:outline-search" /><span>{{ $t('common.query') }}</span></el-button
            >
            <el-button @click="resetSearch" type="info" size="small" plain>
              <Icon icon="icon-park-solid:clear-format" /><span>{{
                $t('common.reset')
              }}</span></el-button
            >
            <el-button type="success" size="small" plain @click="showDialog()">
              <Icon icon="material-symbols:add-circle-rounded" /><span>{{ $t('common.add') }}</span>
            </el-button>
          </div>
        </el-col>
      </el-row>
    </el-card>
    <el-container class="mainArea">
      <el-aside width="200px">
        <ModuleTree @node-click="handleNodeClick" />
      </el-aside>
      <el-main class="formcard">
        <!-- 搜索結果表格 -->
        <el-table
          :data="state.tableView"
          tooltip-effect="light"
          style="width: 100%; border: 1px solid #ddd; font-size: 12px"
          stripe
          row-key="id"
          default-expand-all
          :header-cell-style="{
            background: 'var(--el-color-primary-light-9)',
            color: '#409eff'
          }"
        >
          <el-table-column type="index" min-width="60">
            <template #header>
              <div style="margin-bottom: -10px">
                <Icon
                  icon="ant-design:field-number-outlined"
                  size="24"
                  :title="$t('common.number')"
              /></div>
            </template>
          </el-table-column>
          <el-table-column
            :prop="state.fmNameField"
            :label="$t('form.name')"
            show-overflow-tooltip
            min-width="100"
          />
          <el-table-column prop="status" :label="$t('monitor.type')" min-width="70" align="center">
            <template #default="{ row }">
              <span v-if="row.fmType == 2">{{ $t('form.type2') }}</span>
              <span v-else>PC</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="icon"
            :label="$t('menu.icon')"
            show-overflow-tooltip
            min-width="100"
            align="center"
          >
            <template #default="{ row }">
              <div style="margin-bottom: -5px" v-if="row.icon">
                <Icon :icon="row.icon ? row.icon : ''" color="green" :size="22" />
              </div>
            </template>
          </el-table-column>
          <el-table-column
            :prop="state.modNameField"
            :label="$t('orderNo.module')"
            min-width="110"
          />
          <el-table-column prop="fmCols" :label="$t('form.cols')" min-width="90" align="center" />
          <el-table-column prop="ver" :label="$t('form.ver')" min-width="70" align="center" />
          <el-table-column prop="status" :label="$t('common.status')" min-width="70" align="center">
            <template #default="{ row }">
              <span v-if="row.status == 0">{{ $t('entity.status0') }}</span>
              <span v-else>{{ $t('entity.status1') }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="updateBy" :label="$t('common.updateBy')" min-width="85" />
          <el-table-column prop="updateTime" :label="$t('common.updateTime')" min-width="140" />
          <el-table-column fixed="right" :label="$t('common.operation')" width="210" align="center">
            <template #default="{ row }">
              <el-button
                type="primary"
                plain
                circle
                size="small"
                :title="$t('common.modify')"
                @click="edit(row.fmId)"
              >
                <el-icon>
                  <Edit />
                </el-icon>
              </el-button>
              <el-button
                type="primary"
                plain
                circle
                size="small"
                v-show="row.status == 1"
                :title="$t('form.preview')"
                @click="preview(row.fmId)"
              >
                <Icon icon="icon-park-outline:preview-open" />
              </el-button>
              <el-button
                type="primary"
                plain
                circle
                size="small"
                :title="$t('form.design')"
                @click="design(row.fmId)"
              >
                <Icon icon="logos:vue" />
              </el-button>
              <el-button
                type="danger"
                plain
                circle
                size="small"
                :title="$t('common.delete')"
                v-if="row.isBuildIn != 1"
                @click="deleteOne(row)"
              >
                <el-icon>
                  <Delete />
                </el-icon>
              </el-button>
              <el-button
                type="success"
                plain
                circle
                size="small"
                v-show="row.status == 1"
                :title="$t('dataList.addMenu')"
                @click="add2Menu(row)"
              >
                <Icon icon="ic:sharp-menu-open" />
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分頁器 -->
        <div class="demo-pagination-block"
          ><el-pagination
            v-model:currentPage="state.queryBody.pageNo"
            v-model:page-size="state.queryBody.pageSize"
            @current-change="changePage"
            @size-change="changePageSize"
            :page-sizes="state.pageSizes"
            :background="true"
            layout="total, sizes, prev, pager, next, jumper"
            :total="state.totalCount"
        /></div>
      </el-main>
    </el-container>
  </div>
  <!-- 创建表单对话框 -->
  <el-dialog v-model="state.dialogVisible" :title="$t('form.new')" width="800px" draggable>
    <el-form :model="state.dialogForm" :rules="state.dialogRule" label-width="auto" ref="formRef">
      <el-row>
        <el-col :sm="24" :md="12">
          <el-form-item :label="$t('orderNo.module')" prop="moduleId">
            <el-select
              v-model="state.dialogForm.moduleId"
              :placeholder="$t('common.selectText')"
              size="default"
              @change="refreshEntityList($event)"
            >
              <el-option
                v-for="item in state.moduleList"
                :key="item.moduleId"
                :label="item[state.modNameField]"
                :value="item.moduleId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :sm="24" :md="12">
          <el-form-item :label="$t('form.entity')" prop="entId">
            <el-select
              v-model="state.dialogForm.entId"
              :placeholder="$t('common.selectText')"
              size="default"
            >
              <el-option
                v-for="item in state.entityList"
                :key="item.entId"
                :label="item[state.entNameField]"
                :value="item.entId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :sm="24" :md="12">
          <el-form-item :label="$t('monitor.type')" prop="fmType">
            <el-select
              v-model="state.dialogForm.fmType"
              :placeholder="$t('common.selectText')"
              size="default"
              @change="changeType($event)"
            >
              <el-option key="1" label="PC" value="1" />
              <el-option key="2" :label="$t('form.type2')" value="2" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :sm="24" :md="12">
          <el-form-item
            :label="$t('form.cols')"
            prop="fmCols"
            v-if="state.dialogForm.fmType == '1'"
          >
            <el-input-number
              v-model="state.dialogForm.fmCols"
              :min="1"
              :max="3"
              size="small"
              style="width: 100%"
              controls-position="right"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer" style="text-align: center">
        <el-button @click="createForm()" type="primary" plain :loading="state.createFormLoading">
          <Icon icon="material-symbols:add-circle-rounded" />
          <span> {{ $t('form.new') }}</span></el-button
        >
        <el-button @click="state.dialogVisible = false" plain type="info">
          <Icon icon="ri:arrow-go-back-fill" />
          <span> {{ $t('common.back') }}</span>
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<style lang="less" scoped>
:deep(.el-card__header) {
  border-bottom: 0;
  nav-down: auto;
}

:deep(.el-select .el-option .el-input .el-select-dropdown__item) {
  font-size: 12px;
}

:deep(.el-input__inner) {
  &::placeholder {
    font-size: 12px;
  }
  font-size: 12px;
}

:deep(.v-footer) {
  height: 0px;
}
.mainArea {
  height: calc(100vh - 145px);
  overflow-x: hidden;
}
.formcard {
  margin: -12px -19px 0 -15px;
}
// 分頁器樣式
.demo-pagination-block {
  display: flex;
  justify-content: center;
  justify-items: center;
  margin-top: 20px;
  margin-bottom: 20px;
}
:deep(.el-pagination__sizes > .el-select) {
  margin-top: -3px;
}
:deep(.el-pager li) {
  font-size: 12px;
  height: 28px;
  margin-top: -1px;
}
:deep(.el-pagination span:not([class*='suffix'])) {
  font-size: 12px;
}
</style>
